import { fetchWithAuth } from './auth.js';

const API_BASE_URL = 'http://localhost:3000/api';

// 获取职位列表（支持多条件筛选）
export const getJobList = async (params = {}) => {
  try {
    // 构建查询参数
    const queryParams = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
      if (value) queryParams.append(key, value);
    });

    const result = await fetchWithAuth(
      `${API_BASE_URL}/jobs?${queryParams.toString()}`,
      { method: 'GET' }
    );

    return result.data;
  } catch (error) {
    console.error('获取职位列表错误:', error.message);
    throw error;
  }
};

// 高级搜索职位（支持多条件组合）
export const advancedSearchJobs = async (filters, page = 1, limit = 10) => {
  try {
    // 构建查询参数
    const queryParams = new URLSearchParams();
    Object.entries(filters).forEach(([key, value]) => {
      if (value) queryParams.append(key, value);
    });
    queryParams.append('page', page);
    queryParams.append('limit', limit);

    const result = await fetchWithAuth(
      `${API_BASE_URL}/jobs?${queryParams.toString()}`,
      { method: 'GET' }
    );

    return result.data;
  } catch (error) {
    console.error('高级搜索职位错误:', error.message);
    throw error;
  }
};

// 关键词搜索职位（兼容旧接口）
export const searchJobs = async (keyword, page = 1, limit = 10) => {
  try {
    const result = await fetchWithAuth(
      `${API_BASE_URL}/jobs/search?keyword=${encodeURIComponent(keyword)}&page=${page}&limit=${limit}`,
      { method: 'GET' }
    );

    return result.data;
  } catch (error) {
    console.error('搜索职位错误:', error.message);
    throw error;
  }
};

// 获取职位详情
export const getJobDetails = async (jobId) => {
  try {
    const result = await fetchWithAuth(
      `${API_BASE_URL}/jobs/${jobId}`,
      { method: 'GET' }
    );

    return result.data;
  } catch (error) {
    console.error('获取职位详情错误:', error.message);
    throw error;
  }
};

// 发布职位（企业用户）
export const createJob = async (jobData) => {
  try {
    const result = await fetchWithAuth(
      `${API_BASE_URL}/jobs`,
      {
        method: 'POST',
        body: JSON.stringify(jobData)
      }
    );

    return result.data;
  } catch (error) {
    console.error('发布职位错误:', error.message);
    throw error;
  }
};

// 更新职位（企业用户）
export const updateJob = async (jobId, jobData) => {
  try {
    const result = await fetchWithAuth(
      `${API_BASE_URL}/jobs/${jobId}`,
      {
        method: 'PUT',
        body: JSON.stringify(jobData)
      }
    );

    return result.data;
  } catch (error) {
    console.error('更新职位错误:', error.message);
    throw error;
  }
};

// 删除职位（企业用户）
export const deleteJob = async (jobId) => {
  try {
    const result = await fetchWithAuth(
      `${API_BASE_URL}/jobs/${jobId}`,
      { method: 'DELETE' }
    );

    return result.data;
  } catch (error) {
    console.error('删除职位错误:', error.message);
    throw error;
  }
};

// 渲染职位列表到页面
export const renderJobList = (jobs, containerId) => {
  const container = document.getElementById(containerId);
  if (!container) return;

  if (jobs.length === 0) {
    container.innerHTML = '<div class="no-jobs">暂无职位数据</div>';
    return;
  }

  container.innerHTML = jobs.map(job => `
    <div class="job-card">
      <div class="job-header">
        <h3 class="job-title">${job.title}</h3>
        <span class="job-salary">${job.salaryRange}</span>
      </div>
      <div class="job-company">${job.company?.name || '未知企业'}</div>
      <div class="job-meta">
        <span class="job-location">${job.city}</span>
        <span class="job-experience">${job.experience}</span>
        <span class="job-education">${job.education}</span>
      </div>
      <div class="job-desc">${job.description.substring(0, 100)}${job.description.length > 100 ? '...' : ''}</div>
      <div class="job-actions">
        <a href="job-details.html?id=${job.id}" class="btn btn-primary">查看详情</a>
        ${job.companyId === currentUser?.id ? `
          <button class="btn btn-secondary edit-job" data-id="${job.id}">编辑</button>
          <button class="btn btn-danger delete-job" data-id="${job.id}">删除</button>
        ` : ''}
      </div>
    </div>
  `).join('');
};

// 初始化高级职位搜索功能
export const initAdvancedJobSearch = () => {
  const jobQueryForm = document.querySelector('#job-query form.query-form');
  const jobResultContainer = document.getElementById('job-results-container');

  if (jobQueryForm && jobResultContainer) {
    jobQueryForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      // 获取所有筛选条件
      const filters = {
        keyword: document.getElementById('job-keyword').value.trim(),
        industry: document.getElementById('job-industry').value,
        location: document.getElementById('job-location').value,
        salaryRange: document.getElementById('job-salary').value,
        experience: document.getElementById('job-experience').value,
        jobType: document.getElementById('job-type').value
      };

      try {
        jobResultContainer.innerHTML = '<div class="loading">搜索中...</div>';
        const { jobs, total } = await advancedSearchJobs(filters);
        renderJobList(jobs, 'job-results-container');
        // 显示结果统计
        document.getElementById('job-result-count').textContent = `找到 ${total} 个职位`;
      } catch (error) {
        jobResultContainer.innerHTML = `<div class="error">搜索失败: ${error.message}</div>`;
      }
    });
  }
};

// 初始化关键词职位搜索功能（兼容旧页面）
export const initJobSearch = () => {
  const searchForm = document.getElementById('job-search-form');
  const searchInput = document.getElementById('search-keyword');
  const jobContainer = document.getElementById('job-list-container');

  if (searchForm && searchInput && jobContainer) {
    searchForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      const keyword = searchInput.value.trim();
      if (!keyword) return;

      try {
        jobContainer.innerHTML = '<div class="loading">搜索中...</div>';
        const { jobs } = await searchJobs(keyword);
        renderJobList(jobs, 'job-list-container');
      } catch (error) {
        jobContainer.innerHTML = `<div class="error">${error.message}</div>`;
      }
    });
  }
};

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', () => {
  initJobSearch();
  initAdvancedJobSearch();
  // 自动加载热门职位
  if (document.getElementById('job-list-container')) {
    getJobList({ limit: 10 }).then(({ jobs }) => {
      renderJobList(jobs, 'job-list-container');
    });
  }
});